<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style lang="scss">
a:first-child {
  color: red;
}
      .upload-box {
        width: 200px;
        height: 200px;
        border: 1px dashed #969595;
        border-radius: 5px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;

        input[type="file"] {
          width: 100%;
          height: 100%;
          opacity: 0;
        }
        span {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          font-size: 65px;
          color: #948f8f;
        }
      }
    </style>
  </head>
  <body>
    <div class=""><a href=""
        >Lorem ipsum dolor, sit amet consectetur adipisicing elit. Doloremque
        fugiat libero ipsum tempore. Laborum facilis aut ab amet dolorem iste
        officiis ipsa pariatur animi, doloremque autem perspiciatis ullam vitae
        quasi!</a
      >
      <div class="upload-box">
        <span>+</span>
        <input type="file" id="file" />
      </div>
      <button onclick="uploadFile()">上传</button>
      <button onclick="cancelUpload()">取消上传</button>
      <a href=""
        >Odit, expedita. Error, enim quidem. Nulla vel ipsum minus incidunt
        porro hic quisquam debitis harum ut sit, qui perferendis eaque quidem
        recusandae, maiores molestiae! Voluptate quod optio quis amet
        temporibus.</a
      ><a href=""
        >Officia quo non nam quaerat eum nesciunt vitae deserunt aut, fuga
        repudiandae possimus cum, dolor vero. Rem doloribus sunt consequatur
        iste similique non ut odit possimus et quo. Sint, numquam.</a
      ><a href=""
        >Odio itaque nulla nesciunt provident ad, eveniet aliquam alias optio
        enim ducimus atque! Inventore, officia? Deserunt, deleniti perferendis,
        illum, mollitia reprehenderit aperiam corrupti non et maiores rerum
        velit numquam explicabo!</a
      ><a href=""
        >Alias dolore quae tempora, repudiandae eum a aliquam minima mollitia
        nostrum id molestias culpa ipsam modi dolor cumque? Rem, vitae voluptate
        adipisci delectus ad minima hic eaque ab enim officia.</a
      >
    </div>
    <div id="progress"></div>
    <script>
      let cancelUpload; // 用于取消上传
      let doms = {
        box: document.querySelector(".upload-box"),
        progress: document.getElementById("progress"),
        file: document.getElementById("file"),
      };

      function uploadFile() {
        console.log("开始上传...");
        console.log(doms.file.files[0]);
        const file = document.getElementById("file").files[0];
        if (!file) {
          console.log("请选择文件");
          alert("请选择文件");
          return;
        }
        cancelUpload = uploadBinary(
          file,
          function (progress) {
            console.log(progress);
            doms.progress.innerText = progress + "%";
            if (progress >= 100) {
              alert("上传完成");
            }
          },
          function (resp) {
            console.log(resp);
          }
        );
      }
      function upload(file, onProgress, onFinish) {
        const xhr = new XMLHttpRequest();
        xhr.onload = function () {
          const resp = JSON.parse(xhr.responseText);
          onFinish(resp);
        };
        xhr.upload.onprogress = function (e) {
          if (e.lengthComputable) {
            const progress = (e.loaded / e.total) * 100;
            console.log(progress);
            onProgress(progress);
          }
        };
        xhr.open("POST", "http://localhost:3000/upload/simple/file", true); // true 表示异步
        const formData = new FormData();
        formData.append("file", file);
        xhr.send(formData);

        return function () {
          xhr.abort();
        };
      }

      function uploadBase64(file, onProgress, onFinish) {
        console.log("文件信息：", file);
        onProgress(0);
        const reader = new FileReader();
        let xhr = null;
        reader.onload = function (e) {
          console.log(e.target.result);
          const base64 = e.target.result;

          xhr = new XMLHttpRequest();
          xhr.onload = function () {
            const resp = JSON.parse(xhr.responseText);
            onFinish(resp);
          };
          xhr.upload.onprogress = function (e) {
            if (e.lengthComputable) {
              const progress = (e.loaded / e.total) * 100;
              console.log(progress);
              onProgress(progress);
            }
          };
          xhr.open(
            "POST",
            "http://localhost:3000/upload/simple/base64/file",
            true
          ); // true 表示异步

          xhr.setRequestHeader("Content-Type", "application/json"); // 设置请求头

          const formData = { file: base64, filename: file.name }; // 将文件转换为base64
          xhr.send(JSON.stringify(formData));
        };
        reader.readAsDataURL(file);
        return function () {
          xhr && xhr.abort();
        };
      }

      function uploadBinary(file, onProgress, onFinish) {
        console.log("文件信息：", file);
        const xhr = new XMLHttpRequest();
        xhr.onload = function () {
          const resp = JSON.parse(xhr.responseText);
          onFinish(resp);
        };
        xhr.upload.onprogress = function (e) {
          if (e.lengthComputable) {
            const progress = (e.loaded / e.total) * 100;
            console.log(progress);
            onProgress(progress);
          }
        };
        xhr.open(
          "POST",
          "http://localhost:3000/upload/simple/binary/file",
          true
        ); // true 表示异步
        xhr.setRequestHeader("Content-Type", "application/octet-stream"); // 设置请求头
        xhr.setRequestHeader("x-ext", file.name.split(".").pop()); // 设置请求头
        xhr.setRequestHeader("x-name", file.name); // 设置请求头

        xhr.send(file);

        return function () {
          xhr.abort();
        };
      }
      // 拖拽上传,改变普通元素为拖拽元素
      doms.box.ondragenter = function (e) {
        e.preventDefault();
        doms.box.style.borderColor = "red";
      };
      doms.box.ondragleave = function (e) {
        e.preventDefault();
        doms.box.style.borderColor = "red";
      };
      doms.box.ondrop = function (e) {
        e.preventDefault();
        console.log(e);
        let file = e.dataTransfer.files[0];
        console.log(file);
        const dataTransfer = new DataTransfer();

        // 3. 将 File 对象添加到 DataTransfer 中
        dataTransfer.items.add(file);
        doms.file.files = dataTransfer.files;
        doms.box.style.borderColor = "blue";
      };
    </script>
  </body>
</html>
